﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Diagnostics;
using System.Windows.Forms;
using Contract;
using System.IO;

namespace client
{
            
    public partial class frmClient : Form,callBackContract.IcallbackService
    {

        public static IDataUploader Proxy;
        public NetTcpBinding binding;
        EndpointAddress address;
        ChannelFactory<IDataUploader> channel;
        public frmClient()
        {
            InitializeComponent();
            //////////////////////////////////////
            binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.SendTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            address = new EndpointAddress("net.tcp://localhost:5000/DataUploader");
            channel =new ChannelFactory<IDataUploader>(binding, address);
            IDataUploader Proxy = channel.CreateChannel();
            ///////////////////////////////////////////////
            MyFile[] mfs = Proxy.refreshList();
            UpdateFileList(mfs);
            ((IClientChannel)Proxy).Close();
            hostCallBackService();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            IDataUploader Proxy = channel.CreateChannel();
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();
            string filename = Path.GetFileName(dialog.FileName);
            Stream uploadStream = new FileStream(dialog.FileName, FileMode.Open);
            MyFile moo = new MyFile() { Value = uploadStream, Name = filename, Size = uploadStream.Length };
            Proxy.Upload(moo);
            MyFile[] mfs = Proxy.refreshList();
            UpdateFileList(mfs);
            ((IClientChannel)Proxy).Close();
        }

        public void UpdateFileList(MyFile[] mfs)
        {
            FileList.Items.Clear();
            MyFile[] mfs2 = mfs;
            foreach (var file in mfs)
            {
                ListViewItem item = new ListViewItem(file.Name);
                FileList.Items.Add(item);
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            
            IDataUploader Proxy = channel.CreateChannel();
            if (FileList.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = FileList.SelectedItems[0];

                string path = item.SubItems[0].Text;

                SaveFileDialog dialog = new SaveFileDialog()
                {
                    FileName = Path.GetFileName(path)
                };

                dialog.ShowDialog(this);
                if (dialog.FileName != "")
                {
                    FileStream output = new FileStream(dialog.FileName, FileMode.Create);
                    
                        Stream downloadStream = Proxy.Download(path);
                        byte[] bt = ReadBytestoStream(downloadStream);
                        output.Write(bt, 0, bt.Length);
                        MessageBox.Show("File is Downloaded!");
                        output.Close();

                    Process.Start(dialog.FileName);
                }
                MyFile[] mfs = Proxy.refreshList();
                UpdateFileList(mfs);
                ((IClientChannel)Proxy).Close();

            }
        }

        public static byte[] ReadBytestoStream(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {

            IDataUploader Proxy = channel.CreateChannel();

            if (FileList.SelectedItems.Count == 0)
            {
                MessageBox.Show("No File is Selected");
            }
            else
            {
                ListViewItem item = FileList.SelectedItems[0];

                string path = item.SubItems[0].Text;

                Proxy.Delete(path);
                MyFile[] mfs = Proxy.refreshList();
                UpdateFileList(mfs);
                ((IClientChannel)Proxy).Close();
            }
        }

        //Callback function
        public void onListRefresh()
        {
            IDataUploader Proxy = channel.CreateChannel();
            MyFile[] mfs = Proxy.refreshList();
            UpdateFileList(mfs);
            ((IClientChannel)Proxy).Close();
        }


        public void btnRefresh_Click(object sender, EventArgs e)
        {
            onListRefresh();
        }


        private void hostCallBackService()
        {
            Uri httpUrl = new Uri("net.tcp://localhost:8001/client/");
            //Create ServiceHost
            ServiceHost host
            = new ServiceHost(typeof(frmClient), httpUrl);
            //Add a service endpoint
            host.AddServiceEndpoint(typeof(callBackContract.IcallbackService)
            , new NetTcpBinding(), "");
            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(smb);
            //Start the Service
            host.Open();
        }
    }

   } 
        



        



    